package com.teach.util;

import com.common.bean.Response;
import com.common.exception.RDException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 */
@ControllerAdvice
public class ValidationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> bindExceptionHandler(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult().getFieldErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.toList());
        return new ResponseEntity<>(Response.fail(400, errors.isEmpty() ? "未知的参数错误" : errors.get(0)), HttpStatus.OK);
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public Response<String> constraintViolationExceptionHandler(ConstraintViolationException ex) {
        List<String> errors = ex.getConstraintViolations().stream().map(x -> x.getMessageTemplate()).collect(Collectors.toList());
        return Response.fail(400, errors.get(0));
    }

    @ExceptionHandler({MissingServletRequestParameterException.class})
    public Response<String> requestMissingServletRequest(MissingServletRequestParameterException ex) {
        return Response.fail(400, ex.getMessage());
    }

    @ExceptionHandler({MethodArgumentTypeMismatchException.class})
    public Response<String> requestDataTypeHandler(MethodArgumentTypeMismatchException ex) {
        return Response.fail(400, "数据：[" + String.valueOf(ex.getValue()) + "]不是[" + ex.getParameter().getParameterType().getName() + "]类型");
    }

    @ExceptionHandler({RDException.class})
    public Response<String> logicExceptionHandler(RDException ex) {
        return Response.fail(500, ex.getMessage());
    }
}
